/**
 * Tiem: 2023-1-17
 * FileName: Chauffeur Detail(司机详情，新增，修改)
 * Editor: Haidong
 */

import React, { Component } from "react";
import { Form, Input, InputNumber, Button, Space, Select, Divider } from "antd";
import { CaretDownOutlined } from "@ant-design/icons";
import TheUpload from "@/components/TheUpload";
import TheImage from "@/components/TheImage";
import GoBack from '@/components/TheGoBack';
import { phoneReg } from '@/utils/regexp'
import { apiGetChauffeurDetail, apiPostChauffeurAdd, apiPutChauffeurEdit } from "@/request/petTaxi";
import chauffeurAvatar from '@/assets/images/chauffeur-avatar.png';
import "../style/index.less";
export default class ChauffeurDetail extends Component {
    constructor(props) {
        super();
        this.state = {
            visible: true,
            id: '',
            type: '',
            content: "",
            passwordRules: true,
            confirmPasswordRules: true,
            disabled: false,
            avatar: "",
            fileList: [],
            initialValues: {
                chauffeurname: '',
                phone: '',
                cpassword: '',
                confirmPassword: '',
                status: 1,
                nickname: '',
                avatar: '',
                remark: ''
            }
        }
    }

    //Initialization
    componentDidMount() {
        if (this.props.type === "normal") {
            this.setState({ content: "新增员工" })
        } else {
            this.setState({
                id: this.props.match.params.id,
                type: this.props.match.params.type
            }, () => {
                if (this.state.id === "add") {
                    this.setState({ content: "新增员工" })
                } else {
                    if (this.state.type === "edit") {
                        this.setState({
                            content: "编辑员工",
                            passwordRules: false,
                            confirmPasswordRules: false,
                        })
                    } else {
                        this.setState({
                            content: "查看员工",
                            visible: false,
                            disabled: true
                        })
                    }
                    this.getData(this.state.id)
                }
            })
        }
    }

    //CTRL
    //获取员工信息
    getData = async (driverId) => {
        await apiGetChauffeurDetail(driverId).then(
            res => {
                if (res.code === 0 && res.data) {
                    let data = res.data
                    data.chauffeurname = res.data.username
                    data.cpassword = ""
                    data.confirmPassword = ""
                    let fileList = []
                    if (data.avatar !== "") {
                        fileList = data.avatar.split(',').map((v, k) => {
                            return {
                                name: 'image',
                                uid: k + 1,
                                url: v,
                                status: 'done'
                            }
                        })
                    }
                    this.setState({
                        fileList,
                        avatar: data.avatar !== "" ? data.avatar : chauffeurAvatar
                    }, () => {
                        this.formRef.setFieldsValue(data)
                    })
                }
            }
        ).catch(err => {
            React.$message({
                type: 'warning',
                content: err.code
            })
        })
    }
    // 司机图片
    getFileResult = (value) => {
        let arr = value.map(v => {
            let data = ''
            if (v.response && v.response.code === 0) {
                data = v.response.data
            }
            return data
        })
        let avatar = arr.join(',')
        this.formRef.setFieldsValue({
            avatar
        })
    }
    //密码更改再次确认
    passwordChange = (value) => {
        if (value.target.value) {
            this.setState({
                confirmPasswordRules: true
            })
        } else {
            this.setState({
                confirmPasswordRules: false
            })
        }
    }
    //表单提交
    saveChauffeur = async (value) => {
        if (this.state.id === 'add' || this.props.type === 'normal') {
            value.username = value.chauffeurname
            value.password = value.cpassword
            delete (value.chauffeurname)
            delete (value.cpassword)
            await apiPostChauffeurAdd(value).then(
                res => {
                    if (res.code === 0) {
                        React.$message({
                            type: 'info',
                            content: "添加员工成功"
                        })
                        if (this.props.type === 'normal') {
                            this.props.sumbit({ type: 'save' })
                        } else {
                            this.props.history.goBack()
                        }
                    }
                }
            ).catch(err => {
                React.$message({
                    type: 'warning',
                    content: err.code
                })
            })
        } else {
            value.driverId = this.state.id
            value.username = value.chauffeurname
            if (value.cpassword) {
                value.password = value.cpassword
            }
            delete (value.confirmPassword)
            delete (value.chauffeurname)
            delete (value.cpassword)
            await apiPutChauffeurEdit(value).then(
                res => {
                    if (res.code === 0) {
                        React.$message({
                            type: 'info',
                            content: "编辑员工成功"
                        })
                        this.props.history.goBack()
                    }
                }
            ).catch(err => {
                React.$message({
                    type: 'warning',
                    content: err.code
                })
            })
        }
    }
    cancel() {
        if (this.props.type === 'normal') {
            this.props.sumbit({ type: 'cancel' })
        } else {

            this.props.history.goBack()
        }
    }
    //View
    render() {
        const { visible, content, fileList, btnLoading, passwordRules, confirmPasswordRules, disabled, avatar, initialValues } = this.state
        return (
            <div className="missionsPage">
                <GoBack history={this.props.history} title={content} />
                <Form labelCol={{ span: 3, offset: 0 }} wrapperCol={{ span: 6, offset: 1 }} ref={(ref) => (this.formRef = ref)} onFinish={this.saveChauffeur} initialValues={initialValues} >
                    <div className="title">
                        账号信息 <CaretDownOutlined />
                    </div>
                    <Form.Item label="账号名" name="chauffeurname"
                        rules={[{ required: false, message: '请输入用户名' },
                        { pattern: /^[0-9a-zA-Z_]{1,}$/, message: '只能输入数字与英文字母,"_"' }]}
                    >
                        <Input disabled={disabled} placeholder="账号名可用于登录" maxLength={16} />
                    </Form.Item>
                    <Form.Item label="手机号" name="phone" rules={[{
                        required: true,
                        message: '请输入正确的手机号!'
                    },
                    { pattern: phoneReg, message: '请输入正确的手机号!' }
                    ]} >
                        <InputNumber disabled={disabled} placeholder="手机号可作为登录账号" />
                    </Form.Item>
                    <Form.Item label="密码" name="cpassword" rules={[{
                        required: passwordRules,
                        message: '请输入密码!',
                    },
                    {
                        pattern: /^[0-9a-zA-Z_]{6,16}$/,
                        message: "密码应为字母，数字，'_'，6-16位字符串"
                    }
                    ]}>
                        <Input.Password disabled={disabled} placeholder="请输入新密码" onChange={this.passwordChange} />
                    </Form.Item>
                    <Form.Item label="确认密码" name="confirmPassword" rules={[{
                        required: confirmPasswordRules,
                        message: '请再次输入新密码!'
                    },
                    ({ getFieldValue }) => ({
                        validator(_, value) {
                            if (!value || getFieldValue('cpassword') === value) {
                                return Promise.resolve();
                            }
                            return Promise.reject(new Error('两次密码不一致请重新输入!'));
                        },
                    }),
                    ]}
                        dependencies={['cpassword']}
                    >
                        <Input.Password disabled={disabled} placeholder="请再次输入新密码" />
                    </Form.Item>
                    <Form.Item label="状态" name="status" >
                        <Select defaultValue={1} disabled={disabled} >
                            <Select.Option value={1}>正常</Select.Option>
                            <Select.Option value={2}>禁用</Select.Option>
                        </Select>
                    </Form.Item>
                    <div className="title">
                        个人信息 <CaretDownOutlined />
                    </div>
                    <Form.Item label="昵称" name="nickname">
                        <Input disabled={disabled} placeholder="用户昵称，建议16字以内" />
                    </Form.Item>
                    <Form.Item label="头像" name="avatar" >
                        {disabled && <TheImage src={avatar} width={100} height={100} />}
                        {!disabled && <TheUpload disabled={disabled} maxSize={10} fileList={fileList} getFileResult={this.getFileResult} len={1} />}
                    </Form.Item>
                    <Divider />
                    <Form.Item label="备注" name="remark">
                        <Input.TextArea disabled={disabled} maxLength={200} showCount />
                    </Form.Item>
                    {visible && <Form.Item>
                        <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                            <Space>
                                <Button loading={btnLoading} type='primary' htmlType='submit'
                                >保存</Button>
                                <Button onClick={() => this.cancel()}>取消</Button>
                            </Space>
                        </div>
                    </Form.Item>
                    }
                </Form>
            </div>
        )
    }
}